package com.boot.leetcode;

public class TwoNumberAdd {

    public static  ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int curry=0;
        ListNode res = new ListNode(0);
        ListNode curr = res;
        while(l1 !=null || l2 != null){
            int v1 = l1 !=null? l1.val:0;
            int v2 = l2 !=null? l2.val:0;
            int sum = v1 + v2 + curry;

            curry = sum / 10;
            int curr_v =sum;
            if(sum>10) {
                curry = 1;
                curr_v = sum % 10;
            }
            curr.next = new ListNode(curr_v);
            curr = curr.next;

            l1 = l1 !=null ?l1.next:null;
            l2 = l2 !=null ?l2.next:null;
        }

        if(curry == 1){
            curr.next = new ListNode(1);

        }

        return res.next;
    }

    public static class ListNode {
      int val;
      ListNode next;
      public  ListNode() {}
      public ListNode(int val) { this.val = val; }
      public ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(3);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(1);

        ListNode l2 = new ListNode(9);
        l2.next = new ListNode(9);
        l2.next.next = new ListNode(9);

        ListNode l3 = addTwoNumbers(l1,l2);
        while (l3 !=null){
            System.out.println(l3.val);
            l3 = l3.next;
        }
    }
}
